use strict;
use warnings;
use Test::More qw/no_plan/;
use Test::File;
use Test::File::Contents;
use Test::File::Cleaner;
use File::Temp;
use File::Spec;

BEGIN { use_ok 'Test::WWW::Mechanize::Catalyst', 'Askgene' }

my $mech = Test::WWW::Mechanize::Catalyst->new;

# create a temp file and write some random data inside
my $tmp   = File::Temp->new;
my @chars = ( 'a' .. 'z' );
print {$tmp} join '', map { $chars[ int rand @chars ] } (1) x 100;
$tmp->close;
my $work_dir = Path::Class::dir( File::Temp::tempdir() );

isa_ok( Askgene->model('Queue')->work_dir($work_dir), 'Path::Class::Dir' );

# this dir will be poluted with uploaded files when we're done
my $cleaner = Test::File::Cleaner->new($work_dir);

sub upload_ok {

    # upload the temporary file
    $mech->get_ok('/queue/job/add');

    # done this way so I don't have to maintain the viewport id changes
    my ($file_input) = grep { $_->type eq 'file' } $mech->current_form->inputs;
    my ($submit) = grep { $_->type eq 'submit' } $mech->current_form->inputs;
    ok( $file_input, 'has file input' );
    ok( $submit,     'has submit button' );

    # fill in the upload form and send it
    my $tmp_path = Path::Class::file( File::Spec->splitpath( $tmp->filename ) );
    $file_input->value( $tmp_path->stringify );
    $mech->click( $submit->name );
    ok( $mech->status == 200, 'uploaded file' ) or diag( $mech->content );
}

# upload a file
upload_ok();
my ($uploaded) = $work_dir->children;
file_contents_identical( $tmp, $uploaded );
my $jobs =
  Askgene->model('Database::TheSchwartz::Job')
  ->search_like( { arg => '%' . $uploaded->basename . '%' } );
is( $jobs, 1 ) && $jobs->delete;

# upload file again
upload_ok();
isnt(
    my @children = $work_dir->children,
    'deals with duplicate entries nicely'
);
file_contents_identical(@children);
($uploaded) = grep { $_ ne $uploaded } @children;
$jobs =
  Askgene->model('Database::TheSchwartz::Job')
  ->search_like( { arg => '%' . $uploaded->basename . '%' } );
is( $jobs, 1 ) && $jobs->delete;
